import threading
import etcd3
import time
import setting
import json
import uuid

# 定时器
class Timer(object):
    def __init__(self):
        self.client = etcd3.client(host=setting.ETCD_HOST)

    def run(self):
        while True:
            self.client.put("/rpc/crawl_baidu_com/{}".format(str(uuid.uuid4())), "1")
            time.sleep(10)


class Core(object):
    def __init__(self):
        self.client = etcd3.client(host=setting.ETCD_HOST)
        self.nodes = {}

    def listener_factory(self, event):
        print("aaaaaaaaaaa")
        print(event.key)
        print(event.value)

    def update(self, name, value):
        need_update_tasks = []
        if name in self.nodes:
            for task in value["tasks"]:
                if task not in self.nodes[name]["tasks"]:
                    need_update_tasks.append(task)
        else:
            need_update_tasks = value["tasks"]
        self.nodes[name] = value
        for task in need_update_tasks:
            self.client.add_watch_prefix_callback("/rpc/crawl_baidu_com", self.listener_factory)

    def node_watcher_callback(self, event):
        for event in event.events:
            if event.__class__ == etcd3.events.PutEvent:
                # 创建
                key = str(event.key[6:])
                value = json.loads(event.value)
                self.update(key, value)
            elif event.__class__ == etcd3.events.DeleteEvent:
                # TODO
                print(event.__class__)
            else:
                print("unkown event")

    def run(self):
        self.client.add_watch_prefix_callback("/node", self.node_watcher_callback)


if __name__ == "__main__":
    core = Core()
    core.run()

    timer = Timer()
    timer.run()